<template>
  <div class="photographer-manage-container">
    <el-card class="photographer-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/昵称/手机号/邮箱"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="专长">
            <el-select
              class="status-search"
              v-model="searchForm.specialty"
              placeholder="选择专长"
              clearable
            >
              <el-option label="婚纱摄影" value="wedding" />
              <el-option label="写真" value="portrait" />
              <el-option label="儿童摄影" value="children" />
              <el-option label="全家福" value="family" />
              <el-option label="孕妇照" value="maternity" />
            </el-select>
          </el-form-item>
          <el-form-item label="等级">
            <el-select
              class="status-search"
              v-model="searchForm.level"
              placeholder="选择等级"
              clearable
            >
              <el-option label="初级摄影师" value="1" />
              <el-option label="高级摄影师" value="2" />
              <el-option label="资深摄影师" value="3" />
              <el-option label="首席摄影师" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">添加摄影师</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 摄影师列表 -->
      <el-table v-loading="loading" :data="photographerList" style="width: 100%" border>
        <el-table-column label="摄影师信息" min-width="200">
          <template #default="{ row }">
            <div class="photographer-info">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.nickname?.charAt(0) || row.username.charAt(0) }}
              </el-avatar>
              <div class="info-detail">
                <div class="username">{{ row.username }}</div>
                <div class="nickname" v-if="row.nickname">{{ row.nickname }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="手机号" width="120">
          <template #default="{ row }">
            {{ row.phone || '空' }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="180">
          <template #default="{ row }">
            {{ row.email || '空' }}
          </template>
        </el-table-column>

        <el-table-column label="专长" width="200">
          <template #default="{ row }">
            <el-tag
              v-for="item in row.specialties"
              :key="item"
              :type="getSpecialtyTagType(item)"
              class="specialty-tag"
            >
              {{ getSpecialtyLabel(item) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="等级" width="110" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.level" :max="4" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>

        <!-- <el-table-column label="评分" width="120" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.rating" :max="5" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column> -->

        <!-- <el-table-column prop="samples_count" label="样片数" width="100" align="center" /> -->

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
            <el-button type="success" link @click="handleViewPortfolio(row)"> 作品集 </el-button>
            <el-button
              style="margin-left: 0px"
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '设为离职' : '恢复在职' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑摄影师' : '添加摄影师'"
        width="600px"
      >
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <template v-if="!isEdit">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="editForm.password" type="password" show-password />
            </el-form-item>
          </template>

          <template v-if="isEdit">
            <el-form-item label="头像" class="avatar-item">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange"
                :before-upload="beforeUpload"
                :limit="1"
              >
                <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </template>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>

          <el-form-item label="专长" prop="specialties">
            <el-select v-model="editForm.specialties" multiple placeholder="选择专长">
              <el-option label="婚纱摄影" value="wedding" />
              <el-option label="写真" value="portrait" />
              <el-option label="儿童摄影" value="children" />
              <el-option label="全家福" value="family" />
              <el-option label="孕妇照" value="maternity" />
            </el-select>
          </el-form-item>

          <el-form-item label="等级" prop="level">
            <el-rate v-model="editForm.level" :max="4" show-score text-color="#ff9900" />
          </el-form-item>

          <el-form-item label="简介" prop="description">
            <el-input v-model="editForm.introduction" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type {
  Photographer,
  PhotographerQuery,
  PhotographerSpecialty,
  PhotographerUpdateDto,
} from '@/types/photographer'
import { beforeUpload } from '@/utils/upload'
import {
  getPhotographersList,
  createPhotographer,
  updatePhotographer,
  togglePhotographerStatus,
} from '@/api/photographer'
import type { UploadFile, FileItem } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'
import { uploadAvatarWithUserId } from '@/api/upload'
import { encryptPassword } from '@/utils/encrypt'
import { useRouter } from 'vue-router'

const router = useRouter()
// 搜索表单
const searchForm = reactive<PhotographerQuery>({
  keyword: '',
  specialty: undefined,
  level: undefined,
  page: 1,
  pageSize: 10,
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

const singleFile = reactive<FileItem>({
  uid: '',
  name: '',
  status: 'ready',
})

// 编辑表单
const editForm = reactive<PhotographerUpdateDto & { username: string; password: string }>({
  id: 0,
  username: '',
  password: '',
  nickname: '',
  avatar: '',
  phone: '',
  email: '',
  introduction: '',
  specialties: [],
  level: 1,
})

// 摄影师列表数据
const photographerList = ref<Photographer[]>([])

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  specialties: [
    { required: true, message: '请选择专长', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个专长', trigger: 'change' },
  ],
  level: [{ required: true, message: '请选择等级', trigger: 'change' }],
  description: [{ required: false, message: '请输入简介', trigger: 'blur' }],
})

// 获取专长标签类型
const getSpecialtyTagType = (specialty: PhotographerSpecialty) => {
  const types: Record<PhotographerSpecialty, string> = {
    wedding: 'danger',
    portrait: 'warning',
    children: 'success',
    family: 'info',
    maternity: 'primary',
  }
  return types[specialty]
}

// 获取专长标签文本
const getSpecialtyLabel = (specialty: PhotographerSpecialty) => {
  const labels: Record<PhotographerSpecialty, string> = {
    wedding: '婚纱摄影',
    portrait: '写真',
    children: '儿童摄影',
    family: '全家福',
    maternity: '孕妇照',
  }
  return labels[specialty]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.specialty = undefined
  searchForm.level = undefined
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 添加摄影师
const handleAdd = () => {
  isEdit.value = false
  Object.assign(editForm, {
    username: '',
    password: '',
    nickname: '',
    avator: '',
    phone: '',
    email: '',
    description: '',
    specialty: [],
    level: 1,
    is_active: true,
  })
  dialogVisible.value = true
}

// 编辑摄影师
const handleEdit = (row: Photographer) => {
  isEdit.value = true
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    avatar: row.avatar,
    phone: row.phone,
    email: row.email,
    introduction: row.introduction,
    specialties: row.specialties,
    level: Number(row.level),
    is_active: row.is_active,
  })
  dialogVisible.value = true
}

// 查看作品集
const handleViewPortfolio = (row: Photographer) => {
  router.push(`/portfolio/${row.id}`)
}

// 切换状态
const handleToggleStatus = async (row: Photographer) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '设置为离职' : '恢复为在职'}状态吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    await togglePhotographerStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 处理头像上传
const handleAvatarChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    Object.assign(singleFile, {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    })

    try {
      if (!singleFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      singleFile.status = 'uploading'
      singleFile.percentage = 0

      const response = await uploadAvatarWithUserId(singleFile.raw, editForm.id, (percentage) => {
        singleFile.percentage = percentage
      })

      singleFile.status = 'success'
      editForm.avatar = response.data.data.url
      ElMessage.success('上传成功')
    } catch (error) {
      singleFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

// 保存
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      if (isEdit.value) {
        try {
          await updatePhotographer(editForm.id!, {
            nickname: editForm.nickname,
            phone: editForm.phone,
            email: editForm.email,
            photographer_info: {
              introduction: editForm.introduction,
              specialties: editForm.specialties,
              level: Number(editForm.level),
            },
          })
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('保存失败')
        } finally {
          saveLoading.value = false
        }
      } else {
        try {
          await createPhotographer({
            username: editForm.username,
            password: encryptPassword(editForm.password),
            nickname: editForm.nickname,
            phone: editForm.phone,
            email: editForm.email,
            photographer_info: {
              introduction: editForm.introduction,
              specialties: editForm.specialties,
              level: Number(editForm.level),
            },
          })
          ElMessage.success('创建摄影师成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('创建摄影师失败')
        } finally {
          saveLoading.value = false
        }
      }
    }
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getPhotographersList({
      keyword: searchForm.keyword,
      specialty: searchForm.specialty,
      level: searchForm.level,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    photographerList.value = data.data.items

    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.photographer-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.photographer-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.photographer-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-detail {
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 16px;
  font-weight: bold;
}

.contact {
  font-size: 13px;
  color: #666;
}

.specialty-tag {
  margin-right: 5px;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-uploader:hover .avatar-uploader-icon {
  border-color: #409eff;
  color: #409eff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.status-search {
  width: 120px;
}
</style>
